package com.qfedu.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qfedu.java1234.entity.bo.PageBean;
import com.qfedu.java1234.entity.bo.Role;
import com.qfedu.java1234.entity.bo.RoleMenu;
import com.qfedu.java1234.entity.bo.UserRole;
import com.qfedu.java1234.entity.vo.ResultVO;
import com.qfedu.java1234.service.RoleMenuService;
import com.qfedu.java1234.service.RoleService;
import com.qfedu.java1234.service.UserRoleService;
import com.qfedu.java1234.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName RoleController
 * @Author ykx
 * @Date 2024/4/24 16:56
 * @Version 1.0
 */
@RestController
@RequestMapping("/sys/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserRoleService userRoleService;

    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResultVO listAll() {
        return ResultVO.success(roleService.list());
    }

    /**
     * 根据条件分页查询角色信息
     *
     * @param pageBean
     * @return
     */
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResultVO list(@RequestBody PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<Role> pageResult = roleService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), new QueryWrapper<Role>().like(StringUtil.isNotEmpty(query), "name", query));
        List<Role> userList = pageResult.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList", userList);
        resultMap.put("total", pageResult.getTotal());
        return ResultVO.success(resultMap);
    }

    /**
     * 添加或者修改
     *
     * @param sysRole
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:role:add')" + "||" + "hasAuthority('system:role:edit')")
    public ResultVO save(@RequestBody Role sysRole) {
        if (sysRole.getId() == null || sysRole.getId() == -1) {
            sysRole.setCreateTime(new Date());
            roleService.save(sysRole);
        } else {
            sysRole.setUpdateTime(new Date());
            roleService.updateById(sysRole);
        }
        return ResultVO.success();
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResultVO findById(@PathVariable(value = "id") Integer id) {
        Role sysRole = roleService.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("sysRole", sysRole);
        return ResultVO.success(map);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:role:delete')")
    public ResultVO delete(@RequestBody List<Long> ids) {
        roleService.removeByIds(ids);
        userRoleService.remove(new QueryWrapper<UserRole>().in("role_id", ids));
        return ResultVO.success();
    }

    /**
     * 获取当前角色的权限菜单ID集合
     *
     * @param id
     * @return
     */
    @GetMapping("/menus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public ResultVO menus(@PathVariable(value = "id") Integer id) {
        List<RoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<RoleMenu>().eq("role_id", id));
        List<Long> menuIdList = roleMenuList.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        return ResultVO.success(menuIdList);
    }

    /**
     * 更新角色权限信息
     *
     * @param id
     * @param menuIds
     * @return
     */
    @Transactional
    @PostMapping("/updateMenus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public ResultVO updateMenus(@PathVariable(value = "id") Long id, @RequestBody List<Long> menuIds) {
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("role_id", id));
        List<RoleMenu> sysRoleMenuList = new ArrayList<>();
        menuIds.forEach(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuId);
            sysRoleMenuList.add(roleMenu);
        });
        roleMenuService.saveBatch(sysRoleMenuList);
        return ResultVO.success();
    }

}
